//
//  SQLXMLCommandDelegate.m
//  PrivateTaxCalculator
//
//  Created by albert ma on 12/22/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "TaxRateDatabase.h"
#import <sqlite3.h>

@implementation TaxRateDatabase
@synthesize sqlStatementList = _sqlStatementList;
static NSString * const kEntryElementName = @"statement";
bool volatile isSQLStatement = false;
sqlite3 *pDb;
- (id)init
{
    self = [super init];
    if(self != nil)
    {
        NSMutableArray *tempMutableArray = [[NSMutableArray alloc]init];
        self.sqlStatementList = tempMutableArray;
        [tempMutableArray release];
        
    }
    return self;
}

- (void)dealloc
{
    [self.sqlStatementList release];
    [super dealloc];
}

- (void)create
{
    NSString* fullpathXml =[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"createtable.xml"];
    NSURL *createUrl = [NSURL URLWithString:fullpathXml];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:createUrl];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
}

- (void)clear
{
    NSString* fullpathXml =[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"deletetable.xml"];
    NSURL *createUrl = [NSURL URLWithString:fullpathXml];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:createUrl];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:kEntryElementName])
    {
        isSQLStatement = true;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if(isSQLStatement)
    {
        [self.sqlStatementList addObject:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:kEntryElementName]) {
        isSQLStatement = false;
    }
}


- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"Parse error");
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    int iRet = sqlite3_open("database.db", &pDb);
    if(iRet != SQLITE_OK)
    {
        sqlite3_close(pDb);
    }
    else
    {
        for(NSString* statement in self.sqlStatementList)
        {
            const char *sql = [statement cStringUsingEncoding:NSASCIIStringEncoding];
            sqlite3_exec(pDb, sql, NULL, NULL, NULL);
        }
    }
    sqlite3_close(pDb);
    pDb = NULL;
}
@end
